package com.gitee.elead.mybatisplus;

import java.time.LocalDateTime;

import org.apache.ibatis.reflection.MetaObject;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.gitee.elead.api.ApiUtils;

/**
 * 通用填充类 适用于mybatis plus
 *
 * @author luopeng
 */
public class CommonMetaObjectHandler implements MetaObjectHandler {

	/**
	 * 创建时间
	 */
	private final String createTime = "createdTime";
	/**
	 * 修改时间
	 */
	private final String updateTime = "updatedTime";
	/**
	 * 创建者ID
	 */
	private final String createUid = "createdBy";

	/**
	 * 修改者ID
	 */
	private final String updateUid = "updatedBy";

	@Override
	public void insertFill(MetaObject metaObject) {
		setInsertFieldValByName(createTime, LocalDateTime.now(), metaObject);
		setInsertFieldValByName(createUid, currentUid(), metaObject);
		setInsertFieldValByName(updateTime, LocalDateTime.now(), metaObject);
		setInsertFieldValByName(updateUid, currentUid(), metaObject);
	}

	@Override
	public void updateFill(MetaObject metaObject) {
		setUpdateFieldValByName(updateTime, LocalDateTime.now(), metaObject);
		setUpdateFieldValByName(updateUid, currentUid(), metaObject);
	}

	/**
	 * 获取当前用户ID
	 */
	private String currentUid() {
		String uid = null;
		try {
			 uid = ApiUtils.currentUid();
		} catch (Exception ignored) {
		}
		return uid;
	}

}
